package com.aegis.manage.api;

import cn.hutool.core.collection.CollectionUtil;
import com.aegis.manage.api.dto.SysApiPermissionDTO;
import com.aegis.manage.api.dto.SysAppDTO;
import com.aegis.manage.api.service.AppServiceApi;
import com.aegis.manage.model.dos.AuthApp;
import com.aegis.manage.service.auth.app.AuthAppService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube
 */
@Service
@DubboService
public class AppServiceApiImpl implements AppServiceApi {

    @Autowired
    private AuthAppService authAppService;

    @Override
    public SysAppDTO selectAppByAppId(String appId) {
        AuthApp authApp = authAppService.selectAppByAppId(appId);
        if (authApp == null) {
            return null;
        }
        SysAppDTO sysAppDTO = new SysAppDTO();
        return (SysAppDTO) sysAppDTO.convert(authApp);
    }

    @Override
    public List<SysAppDTO> selectAppList() {
        List<AuthApp> authApps = authAppService.selectAllApps();
        if (CollectionUtil.isEmpty(authApps)) {
            return null;
        }
        return authApps.stream().map(authApp -> (SysAppDTO) new SysAppDTO().convert(authApp)).collect(Collectors.toList());
    }

    @Override
    public List<SysApiPermissionDTO> selectPermissionByAppId(String appId) {
        List<SysApiPermissionDTO> result = authAppService.selectAppApiGroupPermissions(appId)
                .stream()
                .filter(Objects::nonNull)
                .map(sysApiPermission -> (SysApiPermissionDTO)
                        new SysApiPermissionDTO().convert(sysApiPermission))
                .collect(Collectors.toList());
        return result.isEmpty() ? null : result;
    }
}
